#include "tcpserver.h"
#include "widget.h"

TcpServer::TcpServer(QObject *parent):QTcpServer(parent) {}

void TcpServer::incomingConnection(qintptr socket) {
  // 为每个客户端来开辟一个线程
  WorkThread *thread = new WorkThread(socket);
  connect(thread, &WorkThread::showMessage, (Widget *)parent(),
          &Widget::showMessage);

  connect(thread, &WorkThread::onThreadStoped, this,
          &TcpServer::onThreadStoped);

  // 加入到客户端列表中去
  m_workThreadList.push_back(thread);

  // 启动线程
  thread->start();
}

void TcpServer::sendData(const QByteArray &arr) {
  // 分别调用每个线程的发送
  foreach (WorkThread *t, m_workThreadList) {
    t->send(arr);
  }
}

void TcpServer::closeServer() {
  this->close();
  // 停止所有线程
  foreach (WorkThread *t, m_workThreadList) {
    t->stopThread();
    t->deleteLater();
  }
  // 清空客户端列表
  m_workThreadList.clear();
}

void TcpServer::onThreadStoped(WorkThread *th) {
  // 移除线程对象
  m_workThreadList.removeOne(th);
}
